<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

    <title>好好吃面包店</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
<div class="container">
    <div class="form-box">
        <!-- 注册表单 -->
        <form id="registrationForm" class="register-box hidden">
            <h1>register</h1>
            <input type="text" id="name" placeholder="用户名">
            <input type="email" id="email" placeholder="邮箱">
            <input type="password" id="password_reg" placeholder="密码" autocomplete="new-password">
            <input type="password" id="contactInfo" placeholder="联系电话" autocomplete="off">
            <button type="submit">注册</button>
        </form>
        <!-- 登录表单 -->
        <form id="loginForm" class="login-box">
            <h1>login</h1>
            <input type="email" id="loginEmail" placeholder="邮箱">
            <input type="password" id="password_log" placeholder="密码" autocomplete="current-password">
            <button type="submit">登录</button>
        </form>
    </div>
    <div class="con-box left">
        <h2>欢迎来到<span>好好吃面包店</span></h2>
        <p>快来购买你心仪的<span>面包</span>吧</p>
        <img src="images/login.jpg" alt="">
        <p>已有账号</p>
        <button id="showLogin">去登录</button>
        <!-- 添加管理员登录按钮 -->
        <button id="adminLogin">管理员登录</button>
    </div>
    <div class="con-box right">
        <h2>欢迎来到<span>好好吃面包店</span></h2>
        <p>快来看看可爱的<span>面包</span>吧</p>
        <img src="images/register.jpg" alt="">
        <p>没有账号？</p>
        <button id="showRegister">去注册</button>
    </div>
</div>

<script>
    // 要操作到的元素
    let showLogin = document.getElementById('showLogin');
    let showRegister = document.getElementById('showRegister');
    let formBox = document.querySelector('.form-box');
    let registerBox = document.querySelector('.register-box');
    let loginBox = document.querySelector('.login-box');
    let adminLogin = document.getElementById('adminLogin'); // 获取管理员登录按钮

    // 去注册按钮点击事件
    showRegister.addEventListener('click', () => {
        formBox.style.transform = 'translateX(90%)';
        loginBox.classList.add('hidden');
        registerBox.classList.remove('hidden');
    });

    // 去登录按钮点击事件
    showLogin.addEventListener('click', () => {
        formBox.style.transform = 'translateX(0%)';
        registerBox.classList.add('hidden');
        loginBox.classList.remove('hidden');
    });

    // 管理员登录按钮点击事件
    adminLogin.addEventListener('click', () => {
        window.location.href = 'admin_login.html'; // 跳转到管理员登录界面
    });

    // 显示消息的函数
    function displayMessage(msg) {
        const messageElement = document.getElementById('message');
        if (messageElement) {
            messageElement.innerText = msg;
            setTimeout(() => {
                messageElement.innerText = '';
            }, 3000); // 3秒后清除消息
        } else {
            console.error('Message element not found');
        }
    }

    // 处理注册表单提交
    document.getElementById('registrationForm').addEventListener('submit', function(event) {
        event.preventDefault();

        const name = document.getElementById('name').value.trim();
        const email = document.getElementById('email').value.trim();
        const password = document.getElementById('password_reg').value.trim();
        const contactInfo = document.getElementById('contactInfo').value.trim();

        if (!name || !email || !password || !contactInfo ||
            name.includes(' ') || email.includes(' ') || password.includes(' ') || contactInfo.includes(' ')) {
            displayMessage('注册信息中不能包含空格，且不能为空。');
            return; // 阻止表单提交
        }

        const userData = {
            name: name,
            email: email,
            password: password,
            contactInfo: contactInfo
        };

        fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                displayMessage('注册成功！请登录。');
                document.getElementById('registrationForm').reset();
                document.querySelector('.register-box').classList.add('hidden');
                document.querySelector('.login-box').classList.remove('hidden');
            })
            .catch(error => {
                displayMessage('注册失败，请重试。');
                console.error('Error:', error);
            });
    });

    // 处理登录表单提交
    document.getElementById('loginForm').addEventListener('submit', function(event) {
        event.preventDefault();

        const loginEmail = document.getElementById('loginEmail').value.trim();
        const loginPassword = document.getElementById('password_log').value.trim();

        if (!loginEmail || !loginPassword) {
            displayMessage('邮箱和密码不能为空。');
            return;
        }

        const loginData = {
            email: loginEmail,
            password: loginPassword
        };

        fetch('/api/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data && data.token) {
                    localStorage.setItem('authToken', data.token); // 将JWT存储在LocalStorage中
                    displayMessage('登录成功！');
                    window.location.href = 'page1.htm'; // 重定向到受保护的页面
                } else {
                    displayMessage('登录失败，用户名或密码错误。');
                }
            })
            .catch(error => {
                displayMessage('登录失败，请重试。');
                console.error('Error:', error);
            });
    });

</script>

<div id="message"></div> <!-- 确保这个元素存在于HTML中 -->
</body>
</html>